package cn.kgc.vue.service.impl;

import cn.kgc.vue.commons.QueryCondition;
import cn.kgc.vue.commons.ResponseResult;
import cn.kgc.vue.entity.Dept;
import cn.kgc.vue.entity.User;
import cn.kgc.vue.mapper.DeptMapper;
import cn.kgc.vue.mapper.UserMapper;
import cn.kgc.vue.service.DeptService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;

/**
 * @author mengshun
 * @description 针对表【sys_dept】的数据库操作Service实现
 * @createDate 2023-12-07 09:11:34
 */
@Service
public class DeptServiceImpl extends ServiceImpl<DeptMapper, Dept> implements DeptService {


    @Resource
    private UserMapper userMapper;

    @Override
    public ResponseResult getDeptList(QueryCondition<Dept> queryCondition) {

        //  1. 创建分页对象

        Page<Dept> deptPage = new Page<>(queryCondition.getPage(), queryCondition.getLimit());

        // 2. 判定搜索条件
        LambdaQueryWrapper<Dept> lambda = new QueryWrapper<Dept>().lambda();
        lambda.like(StringUtils.isNotEmpty(queryCondition.getQuery().getDeptName()), Dept::getDeptName, queryCondition.getQuery().getDeptName())
                .orderByDesc(Dept::getCreateTime);

        // 3. 数据查询
        baseMapper.selectPage(deptPage, lambda);

        List<Dept> records = deptPage.getRecords();
        long total = deptPage.getTotal();

        HashMap<String, Object> result = new HashMap<>();
        result.put("total",total);
        result.put("pageData",records);

        return ResponseResult.success().data(result);
    }


    @Override
    public ResponseResult deleteDept(Integer deptId) {

        // 1.判定部门是否被占用
        LambdaQueryWrapper<User> lambda = new QueryWrapper<User>().lambda();
        lambda.eq(User::getDeptId,deptId);

        List<User> users = userMapper.selectList(lambda);

        if (users.size()>0){
            return  ResponseResult.fail().message("部门有员工,不能删除");
        }
        // 2.删除部门信息
        baseMapper.deleteById(deptId);


        return ResponseResult.success().message("删除成功");
    }

}




